888E - Maximum Subsequence - CodeForces Solution


bitmasks divide and conquer meet-in-the-middle *1800

Please click on ads to support us..

C++ Code:

// https://codeforces.com/contest/888/problem/E

#include <cstdio>
#include <algorithm>
#include <functional>
#include <vector>
#include <cstring>
using namespace std;
typedef long long ll;
typedef pair<int,int> pi;

int n, m;   // n <= 35
int a[40];  
vector<int> ml, mr;
int ans;

void generate(int l, int r, vector<int> &res) {
    for (int bm = 0; bm < (1 << (r-l+1)); bm++) {
        int sum = 0;
        for (int i = 0; i < r-l+1; i++) {
            if (bm & (1 << i)) 
                sum = (sum + a[l+i]) % m;
        }
        res.push_back(sum);
    }
    sort(res.begin(), res.end());
    res.resize(unique(res.begin(), res.end()) - res.begin());
}

int main() {
    scanf("%d %d", &n, &m);
    for (int i = 0; i < n; i++)
        scanf("%d", &a[i]);
    generate(0, n/2, ml);
    generate(n/2+1, n-1, mr);
    ans = max(ml.back(), mr.back());
    for (int x: ml) {
        auto it = lower_bound(mr.begin(), mr.end(), m-1-x);
        if (it != mr.end() && *it == m-1-x) {
            printf("%d", m-1); return 0;
        }
        if (it == mr.end() || *it > m-1-x && it != mr.begin()) {
            it--;
            ans = max(ans, x + *it);
        }
        // 对于x+y > m,这个一定不如单选x(或y)好,因为(x+y) % m < x
        // ans = max(ans, (x + mr.back()) % m);
    }
    printf("%d\n", ans);

    return 0;
}


Comments

Submit
0 Comments
More Questions

1520A - Do Not Be Distracted
352A - Jeff and Digits
1327A - Sum of Odd Integers
1276A - As Simple as One and Two
812C - Sagheer and Nubian Market
272A - Dima and Friends
1352C - K-th Not Divisible by n
545C - Woodcutters
1528B - Kavi on Pairing Duty
339B - Xenia and Ringroad
189A - Cut Ribbon
1182A - Filling Shapes
82A - Double Cola
45A - Codecraft III
1242A - Tile Painting
1663E - Are You Safe
1663D - Is it rated - 3
1311A - Add Odd or Subtract Even
977F - Consecutive Subsequence
939A - Love Triangle
755A - PolandBall and Hypothesis
760B - Frodo and pillows
1006A - Adjacent Replacements
1195C - Basketball Exercise
1206A - Choose Two Numbers
1438B - Valerii Against Everyone
822A - I'm bored with life
9A - Die Roll
1430B - Barrels
279B - Books